<?php
class Show_360Controller extends ManagerController{
	public function Show_360Controller(){
		parent::ManagerController();
	}
	
	public function delete(){
		$mod = new Show_360Model();
		$show_360 = $mod->get_by_key_site_limit($this->id, 'images');
		if(empty($show_360)){
			self::ajax_error('要删除的记录不存在！');
		}
		//删除记录
		$mod->delete_by_key_site_limit($this->id);
		//删除图片目录
		$show_360_path = ROOT_PATH . '/360/' . SITE_ID . '/' . $this->id;
		yu_del_dir($show_360_path);
		//删除数据库内的文件
		$file_mod = new FileModel();
		$file_mod->delete_by_attr(array(
			'site_id' => SITE_ID,
			'path' => array('$in' => $show_360['images']),
		));
		self::ajax_info('删除成功！');
	}
	
	public function view(){
		$mod = new Show_360Model();
		$show_360 = $mod->get_by_key_site_limit($this->id);
		$this->assign('show_360', $show_360);
		if(count($show_360['images'])<1){
			$this->assign('info', '帧未设置，不能预览！');
			$this->display();
			return;
		}
		for($index=0;$index<$show_360['frame'];++$index){
			// 			echo empty($img)?'1':'0';continue;
			if(empty($show_360['images'][$index])){
				$this->assign('info', '帧不全不能预览！');
				$this->display();
				return;
			}
		}
		$this->display();
	}
	
	public function test(){
		$mod = new Show_360Model();
		$mod->update_by_key_site_limit('9A70C697C25D4A639D2C27B49A24BF91', array('width'=>134));
		
	}
	
	public function index(){
		self::init_page_info();
		$condition = array(
			'site_id' => SITE_ID 
		);
		$mod = new Show_360Model();
		$total = $mod->count($condition);
		if ($total > 0){
			$show_360s = $mod->find($condition, null, $this->page_info->get_start(), $this->page_info->page_size);
			foreach($show_360s as $k => &$p){
				if(isset($p['images'][0])){
					$p['picture'] = $p['images'][0];
				}else{
					$p['picture'] = 'images/no_pic.jpg';
				}
			}
			$this->assign('products', $show_360s);
		}
		self::set_page_total($total);
		$this->display();
		// ImageHandler::image_split('D:\\08.jpg',
	// 'D:\\t',256,256,array("a","de","ef","1","eg","e","4e","tw","ks","4f","t7","6g","jx","et","ss","yd","te"),1,4);
	}
	
	public function edit(){
		if(IS_POST){
			self::save();
		}
		$mod = new Show_360Model();
		$show_360 = $mod->get_by_key_site_limit($this->id);
		foreach($show_360['images'] as $k=>$img){
// 			echo empty($img)?'1':'0';continue;
			if(empty($img)){
				//$show_360['images'][$k] = 'template/images/no_pic.jpg';
			}
		}
		$this->assign('show_360', $show_360);
		$this->display();
	}
	
	public function del_frame(){
		//获取对象
		$mod = new Show_360Model();
		$show_360 = $mod->get_by_key_site_limit($this->id);
		if(empty($show_360)){
			self::ajax_error('未找到记录！');
		}
		$index = self::get_int_val('index', -1);
		if($index < 0){
			self::ajax_error('未指定要删除的帧！');
		}
		$serials = explode(',', $show_360['serials']);
		
		$img_path = ROOT_PATH . '/' . $show_360['images'][$index];
		
		//删除数据库内数据
		$show_360['images'][$index] = '';
		$show_360['frame'] = self::get_360_frame_count($show_360);
		//保存
		$mod->update_by_key_site_limit($this->id, $show_360);
		
		//删除图片
		$base_360_path = ROOT_PATH . '/360/' . SITE_ID . '/' . $this->id . '/';
		self::delete_360_image($base_360_path, $img_path, $serials, $index);
		
		self::ajax_info('delete_success');
	}
	
	public function upload(){
		//获取对象
		$mod = new Show_360Model();
		$show_360 = $mod->get_by_key_site_limit($this->id);
		if(empty($show_360)){
			self::ajax_error('未找到记录！');
		}
		$base_path = 'sites/main/' . MAIN_DOMAIN . '/file/' . date("Y_m") . '/';
		$result = upload_img($base_path, 'imgFile');
		if($result['result']===false){
			//上传失败
			echo json_encode($result);
			exit;
		}
		
		$frame = 0;
		if(isset($_REQUEST['frame'])){
			$frame = intval($_REQUEST['frame']);
		}
		
		//切割图片
		$base_360_path = ROOT_PATH . '/360/' . SITE_ID . '/' . $this->id . '/';
		$serials = explode(',', $show_360['serials']);
		$cut_result = self::create_360_image($base_360_path, ROOT_PATH . '/' . $result['path'], $serials, $frame);
		if($cut_result['result'] === false){
			echo json_encode($cut_result);
			exit;
		}
		
		//切割成功
		if($frame === 0){
			//获取第一张图片的规格
			$first_img_path = $base_360_path . $serials[1] . '_' . $serials[0] . '.jpg';
			if(is_file($first_img_path)){
				list($width, $height) = getimagesize($first_img_path);
				$show_360['width'] = $width;
				$show_360['height'] = $height;
				$show_360['zoom'] = $cut_result['zoom'];
			}
		}
		
		//更新到数据库
		$show_360['images'][$frame] = $result['path'];
		$show_360['frame'] = self::get_360_frame_count($show_360);
		$mod->update_by_key_site_limit($this->id, $show_360);
		$result['data'] = get_thumb_path($result['data'], '100x100');
		echo json_encode($result);exit;
	}
	
	private function get_360_frame_count($show_360){
		if(!isset($show_360['images'])) return 0;
		$count = 0;
		foreach($show_360['images'] as $k=>$img){
			if(!empty($img)) ++$count;
		}
		return $count;
	}
	
	private function save(){
		$name = self::get_post_val('name');
		if(empty($name)){
			self::ajax_error('名称不能为空！');
		}
		$desc = self::get_post_val('desc');
		$show_360 = array(
			'name' => $name,
			'desc' => $desc,
		);
		//处理外网ID
		$ids = array();
		foreach($_POST['out_ids'] as $oid){
			if($oid !== ''){
				$ids[] = $oid;
			}
		}
		array_unique($ids);
// 		$v = var_export($ids, true);
// 		self::ajax_error($v);
		$show_360['out_ids'] = $ids;
		
		$mod = new Show_360Model();
		if(empty($this->id)){
			// 新增
			$id = gen_guid();
			$show_360['_id'] = $id;
			$show_360['frame'] = 0;
			$show_360['site_id'] = SITE_ID;
			// 创建混淆字段
			$serials = Show_360Model::gen_serial();
			$show_360[serials] = implode(',', $serials);
			
			$mod->insert($show_360);
			self::ajax_info('添加成功！', $id);
		} else {
			// 修改
			$mod->update_by_key_site_limit($this->id, $show_360);
			self::ajax_info('修改成功！');
		}
	}
	
	/**
	 * 切割图片
	 * 
	 * @param 商品ID $id        	
	 * @param 图片路径 $image_paths        	
	 */
	private function split_imgs($show_360){
		$id = $show_360['_id'];
		$image_paths = $show_360['images'];
		$base_360_path = ROOT_PATH . '/360/' . SITE_ID . '/' . $id . '/';
		if(!is_dir($base_360_path)){
			yu_mkdirs($base_360_path);
		}
		if(isset($show_360['serials'])){
			$serials = explode(',', $show_360['serials']);
		}else{
			$serials = Show_360Model::gen_serial();
		}
		
		$clock = 0; // 帧数
		foreach($image_paths as $image){
			$img_path = ROOT_PATH . '/' . $image;
			++$clock;
			$this->create_360_image ( $base_360_path, $img_path, $serials, $clock);
		}
	}
	
	
	
	/**
	 * @param base_360_path
	 * @param $img_path
	 * @param serials
	 * @param clock
	 */
	 private function create_360_image($base_360_path, $img_path, $serials, $clock) {
		if(!is_file($img_path)){
			// 图片不存在
			//echo '图片不存在：' . $img_path;
			return array('result'=>false, 'info'=>'图片不存在！');
		}
		$zoom_count = 1;
		list($width, $height) = getimagesize($img_path);
		$max_size = max(array($width, $height));
		while($max_size > Show_360Model::$MIN_ZOOM_SIZE){
			// 计算可放大倍数
			++$zoom_count;
			$max_size /= 2;
		}
	 	$handle = new ImageHandler();
					
		$file_name = preg_replace('%.*?([^.|/]*\.jpg|jpeg|gif|png)%i', '$1', $img_path);
		$type = get_file_ext($file_name);
					
		// 生成压缩图
		for($z = $zoom_count; $z >= 1; --$z){
			$zoom = $zoom_count - $z + 1;
			$rate = pow(2, $z - 1);
			$zoom_img_w = intval($width / $rate);
			$zoom_img_h = intval($height / $rate);
			
			// 缩略图临时路径
			$des_path = $base_360_path . $serials[$zoom] . '_' . $serials[$clock] . $type;
			if(!is_file($des_path)){
				$handle->setSrcImg($img_path);
				$handle->setDstImg($des_path);
				$handle->createImg($zoom_img_w, $zoom_img_h);
			}
			if($zoom <= 2) {
				// 不需要剪切了
			
			}else{
				// 进一步剪切
				$handle->split_360($des_path, $base_360_path, Show_360Model::$SPLIT_SIZE, Show_360Model::$SPLIT_SIZE, $clock, $zoom, $serials);
				
				// 删除大图
				unlink ( $des_path );
			}
		}
		return array('result'=>true, 'info'=>'', 'zoom'=>$zoom_count);
	}
	
	/**
	 * 删除指定360图片
	 * @param string $base_360_path
	 * @param string $img_path
	 * @param array $serials
	 * @param int $clock
	 */
	private function delete_360_image($base_360_path, $img_path, $serials, $clock) {
		if(!is_file($img_path)){
			// 图片不存在
			return;
			//self::ajax_error('图片不存在!');
		}
		$zoom_count = 1;
		list($width, $height) = getimagesize($img_path);
		$max_size = max(array($width, $height));
		while($max_size > Show_360Model::$MIN_ZOOM_SIZE){
			// 计算可放大倍数
			++ $zoom_count;
			$max_size /= 2;
		}
			
		$file_name = preg_replace('%.*?([^.|/]*\.jpg|jpeg|gif|png)%i', '$1', $img_path);
		$type = get_file_ext($file_name);
			
		// 生成压缩图
		for($z = $zoom_count; $z >= 1; --$z){
			$zoom = $zoom_count - $z + 1;
			$rate = pow(2, $z - 1);
			$zoom_img_w = intval($width / $rate);
			$zoom_img_h = intval($height / $rate);
				
			// 缩略图临时路径
			$des_path = $base_360_path . $serials[$zoom] . '_' . $serials[$clock] . $type;
			if($zoom > 2) {
				$x_c = ceil($zoom_img_w / Show_360Model::$SPLIT_SIZE); // X轴可切多少张
				$y_c = ceil($zoom_img_h / Show_360Model::$SPLIT_SIZE); // Y轴可切多少张
				
				for($j=1;$j<=$y_c;++$j){
					for($i=1;$i<=$x_c;++$i){
						$img_name = null;
						if($serials === null){
							$img_name =  $zoom . '_' . $clock. '_' .$j . '_' . $i . '.jpg';
						}else{
							$img_name = $serials[$zoom] . '_' . $serials[$clock] . '_' . $serials[$j] . '_' . $serials[$i] . '.jpg';
						}
						if(is_file($base_360_path . '/' . $img_name)){
							unlink($base_360_path . '/' . $img_name);
						}
					}
				}
			}
			if(is_file($des_path)){
				unlink($des_path);
			}
		}
	}

}

?>